package com.yonyou.brigade.third_parties.tujia.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yonyou.brigade.basic_init.enums.ChannelEnum;
import com.yonyou.brigade.order_center.service.IBriOrderService;
import com.yonyou.brigade.third_parties.tujia.constants.TujiaConstants;
import com.yonyou.brigade.third_parties.tujia.service.ITujiaOrderService;
import com.yonyou.brigade.util.resultutil.HttpSendUtils;
import com.yonyou.brigade.ybz.service.IConvertService;
import com.yonyou.ybzboot.starter.mongodb.dao.IMongoDao;
import com.yonyou.ybzboot.starter.mongodb.model.CriteriaMap;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class TujiaOrderServiceImpl implements ITujiaOrderService {

    Logger logger = LoggerFactory.getLogger(this.getClass());

    @Value("${tujia.queryOrderUrl}")
    private String queryOrderUrl;

    @Value("${tujia.code}")
    private String queryOrderCode;

    @Value("${tujia.tradetype}")
    private String tujiaTradeType;

    @Value("${cnv.baigade.system.code}")
    private String systemCode;

    @Value("${cnv.register.userId}")
    private String cnvRegisterUserId;

    @Value("${cnv.register.tenant}")
    private String cnvRegisterTenant;

    @Value("${cnv.register.cookie}")
    private String cnvRegisterCookie;

    @Autowired
    @Qualifier("convertServiceImpl")
    private IConvertService convertService;

    @Autowired
    @Qualifier("briOrderServiceImpl")
    private IBriOrderService briOrderService;

    @Autowired
    private IMongoDao mongoDao;

    public void getTujiaOrderList(String tenant, String orgPk, String phone, String beginDateTime, String endDateTime, int pagesize, int pagenumber, int channelId){
        Map<String,Object> paramsMap = new HashMap<>();
        paramsMap.put("channelCode",queryOrderCode);
        paramsMap.put("startTime",beginDateTime);
        paramsMap.put("endTime",endDateTime);
        paramsMap.put("userMobile",phone);
        paramsMap.put("pageSize",pagesize);
        Boolean flag = true;
        while (flag){
            paramsMap.put("pageNumber",pagenumber++);
            String result = HttpSendUtils.sendPost(queryOrderUrl, JSON.toJSONString(paramsMap));
            JSONObject response = JSONObject.parseObject(result);
            if (response != null && response.getInteger("resultCode") == 0){
                JSONArray orders = response.getJSONArray("orders");
                //到了最后一页跳出循环
                if (orders.size() < pagesize){
                    flag = false;
                }
                //拉到途家订单，调用转换平台，获得订单中心数据结构的订单
                if (orders != null && orders.size() > 0){
                    for (int i = 0; i < orders.size(); i++) {
                        JSONObject orderJson = orders.getJSONObject(i);
                        dealWithMongo(orderJson.getString("orderNumber"), TujiaConstants.HOTEL_MONGO_ORDER_TABLENAME, orderJson);
                        JSONObject res = convertService.convert(tujiaTradeType, systemCode, cnvRegisterUserId, cnvRegisterTenant, cnvRegisterCookie, orderJson);
                        if (res.getBoolean("success")){
                            JSONArray results = res.getJSONArray("result");
                            if (results != null && results.size() > 0){
                                for (int j = 0; j < results.size(); j++) {
                                    JSONObject jsonObject = results.getJSONObject(j);
                                    JSONObject orderCenter = JSON.parseObject(jsonObject.getString("data"));
                                    if (orderCenter != null && orderCenter.size() > 0) {
                                        String orderNo = orderCenter.getString("orderNo");
                                        String userMobile = orderCenter.getString("userId");
                                        try {
                                            briOrderService.saveHotel(orderCenter, orderNo, tenant, userMobile, ChannelEnum.TUJIA.getName(), channelId);
                                        } catch (ParseException e) {
                                            e.printStackTrace();
                                            logger.error("保存途家酒店订单时，日期类型转换出现错误",e.getMessage());
                                        }
                                    }
                                }
                            }
                        }
                    }
                } else {
                    flag = false;
                }
            } else {
                flag = false;
                logger.error("调用途家订单查询接口返回的错误信息为：" + response.getString("resultMessage"));
            }
        }
    }

    private void dealWithMongo(String orderId, String mongoName, JSONObject orderJson) {
        CriteriaMap criteriaMap = new CriteriaMap();
        criteriaMap.put("orderNumber",orderId);
        List<JSONObject> ordersources = mongoDao.findByMap(criteriaMap, JSONObject.class, mongoName);
        if(ordersources != null && ordersources.size() > 0) {
            mongoDao.deleteByMap(criteriaMap, mongoName);
            mongoDao.getMongoTemplate().save(orderJson, mongoName);
        }
        else {
            mongoDao.getMongoTemplate().insert(orderJson, mongoName);
        }
    }
}
